package cn.yuan.basic.controller;

import cn.yuan.basic.util.FastDfsUtil;
import cn.yuan.util.AjaxResult.AjaxResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true, value = "file") MultipartFile file) {
        try {
            System.out.println(file.getOriginalFilename() + ":" + file.getSize());
            String originalFilename = file.getOriginalFilename();//获取从group前面那个/开始的路径（/group1/M00/00/7F/rBEAA2Bhe8WAfwh4AAhm9Kiy4Ic146.jpg）
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);//xxx.jpg
            System.out.println(extName);
            String filePath = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(filePath); //把上传后的路径返回回
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("上传失败!"+e.getMessage());
        }
    }

    /**
     * 参数：完整路径 /goup1/xxxxx/yyyy
     * 返回值：成功与否，还要返回地址
     *
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path){
        String substring = path.substring(1);// goup1/xxxxx/yyyy
        String substring1 = substring.substring(0, substring.indexOf("/"));//获取goup1
        String substring2 = substring.substring(substring.indexOf("/") + 1);//   /xxxxx/yyyy
        FastDfsUtil.delete(substring1, substring2);// 删除组和文件
        return AjaxResult.me();
    }
}
